﻿namespace UpgradeTool
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using Controllers;
    using System.IO;
    using System.Diagnostics;
    using System.Text.RegularExpressions;
    using System.Threading;

    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
            this.ResultWindow.MouseWheel += new System.Windows.Forms.MouseEventHandler(this.ResultWindow_MouseWheel);
        }

        /// <summary>
        /// Start loading and comparing files
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StartButton_Click(object sender, EventArgs e)
        {
            if (CheckFilesExists(CompareControl.PreviusSelectPath.Text) && CheckFilesExists(CompareControl.CustomerSelectPath.Text) && CheckFilesExists(CompareControl.NextSelectPath.Text) && CheckFilesExists(BCompareSelectPath.Text))
            {
                LoadInputFilesController.Load(CompareControl.PreviusSelectPath.Text, CompareControl.CustomerSelectPath.Text, CompareControl.NextSelectPath.Text, BCompareSelectPath.Text);
                LoadComparedFilesController.Load(LoadInputFilesController.Previus, LoadInputFilesController.Customer, LoadInputFilesController.Next);

                if ((ResultSelectPath.TextLength != 0) && (CheckFilesExists(ResultSelectPath.Text)))
                {
                    LoadResultFileController.ResultFile = ResultSelectPath.Text;
                    ResultFileIndicator.Text = "Loaded file -->";
                }
                else
                {
                    LoadResultFileController.Load(LoadInputFilesController.Previus, LoadInputFilesController.Customer, LoadInputFilesController.Next);
                    ResultFileIndicator.Text = "Merged file -->";
                }

                LoadResultFile(LoadResultFileController.ResultFile);

                CompareControl.leftBrowser.Navigate(LoadComparedFilesController.Previus);
                CompareControl.centralBrowser.Navigate(LoadComparedFilesController.Customer);
                CompareControl.rightBrowser.Navigate(LoadComparedFilesController.Next);

                CompareWebBrowsersWithResult.Load(LoadInputFilesController.Previus, LoadInputFilesController.Customer, LoadInputFilesController.Next, LoadResultFileController.ResultFile);
                RebuildWebBrowsers.Enabled = false;
            }
            else
            {
                MessageBox.Show("Wrong files path!");
            }
        }

        /// <summary>
        /// Load file to merged Window (forth near window)
        /// </summary>
        /// <param name="filename">The name of merged file</param>
        private void LoadResultFile(string filename)
        {
            if (ResultWindow.Text.Length != 0)
            {
                ResultWindow.Text = "";
            }
            string stringtoMergeWindow = default(string);
            StreamReader tempFile = ReadFile(filename);
            while (!tempFile.EndOfStream)
            {
                stringtoMergeWindow = stringtoMergeWindow + tempFile.ReadLine() + "\n";
            }
            tempFile.Close();
            stringtoMergeWindow = stringtoMergeWindow.Remove(stringtoMergeWindow.Length - 1, 1);
            ResultWindow.AppendText(stringtoMergeWindow);
            ResultWindow.Margins[0].Width = 30;
            ResultWindow.ConfigurationManager.Language = "xml";
            ResultWindow.ConfigurationManager.Configure();
            ResultWindow.Lexing.Colorize();
        }

        /// <summary>
        /// Checking specified files exesting
        /// </summary>
        /// <param name="FileFromTextBox">File name to check</param>
        /// <returns>True if file exists, False if file not exists</returns>
        private static bool CheckFilesExists(string FileFromTextBox)
        {
           return File.Exists(FileFromTextBox);
        }

        /// <summary>
        /// Reading file with checking if it exist
        /// </summary>
        /// <param name="file">The name of the file</param>
        /// <returns>StreamReader for this file</returns>
        public static StreamReader ReadFile(string file)
        {
            StreamReader ReturnStreamReader = null;
            while (ReturnStreamReader == null)
            {
                try
                {
                    ReturnStreamReader = new StreamReader(file);
                }
                catch (Exception)
                {
                    Thread.Sleep(100);
                }
            }

            return ReturnStreamReader;
        }

        /// <summary>
        /// Scrolling WebBrowsers windows according ResultWindow
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ResultWindow_Scroll(object sender, ScrollEventArgs e)
        {
            int LeftKoef = CompareControl.leftBrowser.Document.Body.ScrollRectangle.Height / LoadComparedFilesController.NodeCount;
            CompareControl.CompareScrolling(e.NewValue * LeftKoef);
        }

        /// <summary>
        /// It's a temporary input for development!!!
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
            CompareControl.PreviusSelectPath.Text = @"E:\Upgrade\UpgradeTool\FilesExamples\920SP6\1.xml";
            CompareControl.NextSelectPath.Text = @"E:\Upgrade\UpgradeTool\FilesExamples\930SP5\1.xml";
            CompareControl.CustomerSelectPath.Text = @"E:\Upgrade\UpgradeTool\FilesExamples\Customer\1.xml";
            BCompareSelectPath.Text = @"C:\Program Files\Beyond Compare 3\BCompare.exe";
            RebuildWebBrowsers.Enabled = false;
        }

        /// <summary>
        /// Selection lines in WebBrowsers according the line in ResultWindow
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ResultWindow_Click(object sender, EventArgs e)
        {
            object[] PreviusArgs = { CompareWebBrowsersWithResult.PreviusPosition[ResultWindow.Lines.FromPosition(ResultWindow.CurrentPos).Number + 1] };
            CompareControl.leftBrowser.Document.InvokeScript("Selection", PreviusArgs);
            object[] CustomerArgs = { CompareWebBrowsersWithResult.CustomerPosition[ResultWindow.Lines.FromPosition(ResultWindow.CurrentPos).Number + 1] };
            CompareControl.centralBrowser.Document.InvokeScript("Selection", CustomerArgs);
            object[] NextArgs = { CompareWebBrowsersWithResult.NextPosition[ResultWindow.Lines.FromPosition(ResultWindow.CurrentPos).Number + 1] };
            CompareControl.rightBrowser.Document.InvokeScript("Selection", NextArgs);
        }

        /// <summary>
        /// Compare WebBrowsers with result and
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RebuildWebBrowsers_Click(object sender, EventArgs e)
        {
            System.IO.File.WriteAllText(@"TempResult.xml", ResultWindow.Text);
            CompareWebBrowsersWithResult.Load(LoadInputFilesController.Previus, LoadInputFilesController.Customer, LoadInputFilesController.Next, @"TempResult.xml");
            RebuildWebBrowsers.Enabled = false;
        }

        /// <summary>
        /// Scrolling Result Window
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ResultWindow_MouseWheel(object sender, MouseEventArgs e)
        {
            ScrollEventType ty = new ScrollEventType();
            ScrollEventArgs SE = new ScrollEventArgs(ty, ResultWindow.Lines.FirstVisibleIndex);
            ResultWindow_Scroll(sender, SE);
        }

        private void ResultWindow_TextInserted(object sender, ScintillaNET.TextModifiedEventArgs e)
        {
            RebuildWebBrowsers.Enabled = true;
        }

        private void ResultWindow_TextDeleted(object sender, ScintillaNET.TextModifiedEventArgs e)
        {
            RebuildWebBrowsers.Enabled = true;
        }

        private void ResultWindow_TextChanged(object sender, EventArgs e)
        {
            RebuildWebBrowsers.Enabled = true;
        }

        private void ResultSelectButton_Click(object sender, EventArgs e)
        {
            if (openFileDialogForResultFile.ShowDialog() == DialogResult.OK)
            {
                ResultSelectPath.Text = openFileDialogForResultFile.FileName;
            }
        }

        private void SaveResultFile_Click(object sender, EventArgs e)
        {
            saveFileDialogForResultFile.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*";
            saveFileDialogForResultFile.FilterIndex = 2;
            saveFileDialogForResultFile.RestoreDirectory = true;

            if (saveFileDialogForResultFile.ShowDialog() == DialogResult.OK)
            {
                System.IO.File.WriteAllText(saveFileDialogForResultFile.FileName, ResultWindow.Text);
            }
        }

        private void ReloadResultFile_Click(object sender, EventArgs e)
        {
            if ((ResultSelectPath.TextLength != 0) && (CheckFilesExists(ResultSelectPath.Text)))
            {
                LoadResultFileController.ResultFile = ResultSelectPath.Text;
                LoadResultFile(LoadResultFileController.ResultFile);
                ResultFileIndicator.Text = "Loaded file -->";
                RebuildWebBrowsers.Enabled = true;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (openFileDialogForResultFile.ShowDialog() == DialogResult.OK)
            {
                BCompareSelectPath.Text = openFileDialogForResultFile.FileName;
            }
        }
    }
}
